﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.SessionState;

namespace RC1.student
{
    public partial class view_assignment : System.Web.UI.Page
    {
        int assignment_id;
        int user_id;
        int class_id;
        
        DateTime deadline;

        protected void Page_Load(object sender, EventArgs e)
        {
            assignment_id = Convert.ToInt32(Session["assignment_id"]);
            user_id = Convert.ToInt32(Session["user_id"]);
            class_id = Convert.ToInt32(Session["class_id"]);

            populatePage();
        }

        private int storeFile(tsu2011db4Entities1 db)
        {
            string filepath = FileUpload1.PostedFile.FileName;
            string fileExtension = System.IO.Path.GetExtension(filepath).Replace(".", string.Empty).ToLower();
            string fileName = System.IO.Path.GetFileName(filepath);

            // filecontent, convert from stream to byte array
            byte[] fileContent = new byte[FileUpload1.PostedFile.ContentLength];
            FileUpload1.PostedFile.InputStream.Read(fileContent, 0, FileUpload1.PostedFile.ContentLength);

            //Create new file
            file f = new file()
            {
                file_name = fileName,
                file_type = fileExtension,
                file_size = FileUpload1.PostedFile.ContentLength,
                file_content = fileContent
            };

            db.files.AddObject(f);
            db.SaveChanges();

            var fileData = (from f2 in db.files
                            orderby f2.file_id descending
                            select f2).Take(1).SingleOrDefault();
            return fileData.file_id;
        }

        private void populatePage()
        {
            tsu2011db4Entities1 db = new tsu2011db4Entities1();
            var result = (from a in db.assignments
                          where a.assignment_id == this.assignment_id
                          select a).SingleOrDefault();
            Label1.Text = result.assignment_title;
            Label2.Text = result.assignment_description;
            Label3.Text = result.assignment_deadline.ToString();
            if (result.assignment_deadline > DateTime.Now)
            {
                TimeSpan remaingTime = (DateTime)result.assignment_deadline - DateTime.Now;
                Label5.Text = remaingTime.Days.ToString() + " dagar, " + remaingTime.Hours.ToString() + " t " + remaingTime.Minutes.ToString() + " m " + remaingTime.Seconds.ToString() + " s";
                if (remaingTime.Days < 1)
                {
                    Label5.ForeColor = System.Drawing.Color.Orange;
                }
                else
                {
                    Label5.ForeColor = System.Drawing.Color.Green;
                }
            }
            else
            {
                Label5.Text = "Freistin er farin";
                Label5.ForeColor = System.Drawing.Color.Red;
            }

            deadline = result.assignment_deadline;

            var user_info = (from ui in db.user_info
                             where ui.user_id == user_id
                             select ui).SingleOrDefault();
            Label4.Text = user_info.user_info_first_name + " " + user_info.user_info_last_name;


            var submission = (from s in db.submissions
                              join f in db.files on s.file_id equals f.file_id
                              where s.assignment_id == assignment_id
                              where s.user_id == user_id
                              select new
                              {
                                  submission_date = s.submission_date,
                                  file_name = f.file_name,
                                  file_id = f.file_id
                              }).SingleOrDefault();

            if (submission != null)
            {
                String content = "<h3>Latið inn</h3>";
                content = "<table cellpadding='5' width='100%'>";
                content += "<tr><td class='style1'>Lati inn</td><td>" + submission.submission_date + "</td></tr>";
                content += "<tr><td class='style1'>Fílur</td><td><a href='../downloadFile.aspx?id=" + submission.file_id + "'>" + submission.file_name + "</a></td></tr>";
                content += "</table>";
                submissionLable.Text = content;
            }
            else
            {
                submissionLable.Visible = false;
            }          
        }

        private void submittAssignment()
        {
            if (deadline >= DateTime.Now)
            {         
                if (FileUpload1.FileName != String.Empty)
                {
                    tsu2011db4Entities1 db = new tsu2011db4Entities1();

                    //CHECK IF AN SUBMISSION ALREADY EXISTS
                    var r = (from s in db.submissions
                             where s.assignment_id == this.assignment_id
                             where s.user_id == this.user_id
                             select s).SingleOrDefault();

                    if (r != null)
                    {
                        var file = (from f in db.files
                                    where f.file_id == r.file_id
                                    select f).SingleOrDefault();
                        db.files.DeleteObject(file);
                        db.submissions.DeleteObject(r);
                        db.SaveChanges();
                    }

                    //ADD SUBMISSION

                    //STORE THE FILE IN THE DB
                    int fileID = storeFile(db);

                    //CREATE THE SUBMISSION
                    submission sub = new submission()
                    {
                        assignment_id = this.assignment_id,
                        file_id = fileID,
                        submission_date = DateTime.Now,
                        user_id = this.user_id
                    };
                    db.submissions.AddObject(sub);
                    db.SaveChanges();

                    Server.Transfer("viewClass.aspx?id=" + class_id);
                }
                else
                {

                    printError("Ongin fíla vald");
                }
                
            }
            else
            {
                printError("Freistin er farin");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            submittAssignment();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("viewClass.aspx?id=" + class_id);
        }

        private void printError(String s)
        {
            errorLabel.Text = "<tr><td colspan='2'><span style='color:red;'><center>"+s+"</center></span></td></tr>";
            errorLabel.Visible = true;
        }
    }
}